package cn.lwj.controller;


import cn.lwj.pojo.Student;
import cn.lwj.service.StudentService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

/**
 * 仅仅用于测试spring提供的cache功能
 */
//@RestController
@RequestMapping("/student")
public class StudentController{

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private StudentService studentService;


    /**
     * 查询操作  所以使用 @Cacheable(value = "stuCache",key = "#student.id")
     * condition 满足条件的情况下 缓存数据
     * unless 满足条件的情况下不缓存数据
     * @param student
     * @return
     */
//    注意 condition 属性不可以使用#result来进行判断 但是unless可以
    @Cacheable(value = "stuCache",key = "#student.id",unless = "#result == null")
    @GetMapping
    public String getById(Student student){
        Student s = studentService.getById(student.getId());
        if(s != null){
            String stuJsonStr = JSON.toJSONString(s);
            return stuJsonStr;
        }else {
            return "查询失败";
        }
    }

        /**
     * 新增操作所以使用 @CachePut(value = "stuCache",key = "#p0.id")
     * @param student
     */
    @PostMapping
    @CachePut(value = "stuCache",key = "#student.id")
    public String save(Student student){
        boolean res = studentService.save(student);
        if(res){
            return "保存成功";
        }else{
            return "保存失败";
        }
    }

    /**
     * 更新操作和删除操作使用 @CacheEvict(value = "stuCache",key = "#p0.id")
     * 保证数据库和缓存数据的一致性
     * @param student
     */
    @PutMapping
    @CacheEvict(value = "stuCache",key = "#p0.id")
    public void update(Student student){

    }

}
